import Vue from 'vue'
import VueRouter from 'vue-router'
import { Toast } from 'vant'

import { getToken } from '@/utils/storage.js'

import Layout from '@/views/layout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/register',
    component: () => import('@/views/register.vue')
  },
  {
    path: '/article/:id',
    component: () => import('@/views/detail.vue')
  },
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: '/article', component: () => import('@/views/article.vue') },
      { path: '/like', component: () => import('@/views/like.vue') },
      { path: '/collect', component: () => import('@/views/collect.vue') },
      { path: '/user', component: () => import('@/views/user.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫：
// 1. 所有的路由一旦被匹配到，在真正渲染解析之前，都会先经过全局前置守卫
// 2. 只有全局前置守卫放行，才能看到真正的页面

// 任何路由，被解析访问前，都会先执行这个回调 (to, from, next) => {}
// 1. from 你从哪里来， 从哪来的路由信息对象
// 2. to   你往哪里去， 到哪去的路由信息对象
// 3. next() 是否放行，如果next()调用，就是放行 => 放你去想去的页面
//    next(路径) 拦截到某个路径页面

const whiteList = ['/login', '/register']

// 路由全局前置守卫的语法
router.beforeEach((to, from, next) => {
  const token = getToken()

  if (token) {
    // 判断是否有token，如有则直接放行
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('游客请登录！')
      next('/login')
    }
  }
})

export default router
